/*
 * Project: Digital Wristwatch
 * Author: Zak Kemble, contact@zakkemble.co.uk
 * Copyright: (C) 2013 by Zak Kemble
 * License: GNU GPL v3 (see License.txt)
 * Web: http://blog.zakkemble.co.uk/diy-digital-wristwatch/
 */
#include <avr/io.h>
#include <avr/pgmspace.h>
#include "common.h"
#include "global.h"

byte SP_ReadCalibrationByte(byte location) 
{
	byte result;
	/* Load the NVM Command register to read the calibration row. */
	NVM_CMD = NVM_CMD_READ_CALIB_ROW_gc;
 	result = pgm_read_byte(location);
	/* Clean up NVM Command register. */
 	NVM_CMD = NVM_CMD_NO_OPERATION_gc;
	return result;
}

void clock_init(void)
{
	//Chang system clock to ext 16M clock

	DFLLRC32M.CTRL = 0;

	CCP = CCP_IOREG_gc; //Security Signature to modify clock 
	CLK.CTRL = CLK_SCLKSEL_RC2M_gc; // Run at 2M

	OSC.CTRL = OSC_RC2MEN_bm;

	OSC.XOSCCTRL = 0xCB;	// Crystal type 0.4-16 MHz XTAL - 16K CLK Start Up time
	OSC.CTRL = OSC_RC2MEN_bm | OSC_XOSCEN_bm;

	while(!testbit(OSC.STATUS,OSC_XOSCRDY_bp));//wait

	CCP = CCP_IOREG_gc; //Security Signature to modify clock 
	CLK.CTRL = CLK_SCLKSEL_XOSC_gc; // Use xosc as system clock

	OSC.CTRL =  OSC_XOSCEN_bm;	 // Disable internal 2MHz

	PR.PRPD  = 0x6D;        // Stop: TWI, USART1, SPI, HIRES, TC0

#if EXT_USART_EN == 0
    PR.PRPE  = 0x7F;        // Stop: ALL
#endif

	USB.CTRLA = 0x00;
}

#if 0
void clock_sleep(void)
{
	OSC.CTRL = OSC_RC2MEN_bm | OSC_XOSCEN_bm;
	while(!testbit(OSC.STATUS,OSC_RC2MRDY_bp));//wait

	CCP = CCP_IOREG_gc; //Security Signature to modify clock 
	CLK.CTRL = CLK_SCLKSEL_RC2M_gc; // Run at 2M

	OSC.CTRL = OSC_RC2MEN_bm;
}

void clock_wake(void)
{
	OSC.CTRL = OSC_RC2MEN_bm | OSC_XOSCEN_bm;
	while(!testbit(OSC.STATUS,OSC_XOSCRDY_bp));//wait

	CCP = CCP_IOREG_gc; //Security Signature to modify clock 
	CLK.CTRL = CLK_SCLKSEL_XOSC_gc; // Use xosc as system clock

	OSC.CTRL =  OSC_XOSCEN_bm;	 // Disable internal 2MHz
}
#endif
